var workspace;
var code;
workspace = Blockly.inject('blocklyDiv', {
	media: './media/',
	toolbox: document.getElementById('toolbox'),
	zoom: {
		controls: true,
		startScale: 1.2
	},
	trashcan: true
});

$(".blocklyScrollbarHandle").eq(0).css('width',10+'px');
$(".blocklyScrollbarHandle").eq(0).css('opacity','1');
$(".blocklyScrollbarHandle").eq(0).css('fill','gray');
//$(".blocklyScrollbarHandle").eq(1).css('height',10+'px');
//$(".blocklyScrollbarHandle").eq(1).css('opacity','1');
//$(".blocklyScrollbarHandle").eq(1).css('fill','gray');
//打开新建项目对话框
$("#creatprogram").on('click', function() {
	$("#creatpromodal").css('display', 'block');
});
//关闭新建项目对话框
$("#closebtn").on('click', function() {
	$("#creatpromodal").css('display', 'none');
	$("#programname").val('');
});
var routeContent = document.getElementById("route_content");
//确定新建项目 按钮
$("#submitbtn").on('click', function() {
	$("#creatpromodal").css('display', 'none');
	//将用户新建的文件名设为浏览器标题
	//$("title").eq(0).html($("#programname").val());

	//发送到控制器
	if(data_runstate == "stop" && data_model == "A"){
		if(conn) {
			var tmp_name = $("#programname").val();
			var upg_name = tmp_name+".UPG";
			var xml_name = tmp_name+".XML";

			data_file_name = tmp_name;		//缓存当前文件名 前缀

			doUpLoadFile(xml_name,"");				//新建xml

			doUpLoadFile(upg_name,"");				//新建upg
		}
		else{
			log(xml_name+" create failed!");
		}
	}
	else{
		log("机器正在运行或不是自动模式,不可操作文件");
	}

	//清空用户输入框的内容
	$("#programname").val('');
	
	//刷新程序界面
	$("#blocklyDiv").html('');
	setTimeout(work, 10);
	function work() {
		workspace = Blockly.inject('blocklyDiv', {
			media: './media/',
			toolbox: document.getElementById('toolbox'),
			zoom: {
				controls: true,
				startScale: 1.2
			},
			trashcan: true
		});
		//获取代码
		workspace.addChangeListener(rightCodeEvent);
		function rightCodeEvent(masterEvent) {
			if(masterEvent.type == Blockly.Events.UI) {
				return;
			}
			code = Blockly.JavaScript.workspaceToCode(workspace) || '';
		}
	}
});

//获取代码
workspace.addChangeListener(rightCodeEvent);
function rightCodeEvent(masterEvent) {
	if(masterEvent.type == Blockly.Events.UI) {
		return;
	}
	code = Blockly.JavaScript.workspaceToCode(workspace) || '';
}
//获取xml文件
var dom;
var xml;
//保存文件: 代码按钮
$("#saveprogram").on('click', function() {
	dom = Blockly.Xml.workspaceToDom(workspace);
	xml = Blockly.Xml.domToText(dom);
	console.log(code);
	console.log(xml);

	//发送到控制器
	if(data_runstate == "stop" && data_model == "A")
	{
	    if(conn) {
			var tmp_name = data_file_name;
			var upg_name = tmp_name+".UPG";
			var xml_name = tmp_name+".XML";

			doUpLoadFile_overide(xml_name,xml);				//新建xml

			doUpLoadFile_overide(upg_name,code);			//新建upg
		}
	}
	else
	{
		log("机器正在运行或不是自动模式,不可操作文件");
	}
	
	//将xml保存在本地
	//export_raw($("title").eq(0).html()+'.xml', xml);
});
//保存到本地
//function fake_click(obj) {
//	var ev = document.createEvent("MouseEvents");
//	ev.initMouseEvent(
//		"click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null
//	);
//	obj.dispatchEvent(ev);
//}
//function export_raw(name, data) {
//	var urlObject = window.URL || window.webkitURL || window;
//	var oblob = new Blob([data]);
//	var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
//	save_link.href = urlObject.createObjectURL(oblob);
//	save_link.download = name;
//	fake_click(save_link);
//}


//文件名
// var allFileName=[
// 		{"name":"AAA"},
// 		{"name":"BBB"},
// 		{"name":"EEy"}
// 	];

//打开文件名选择框
// $("#openFileName").on('click',function(){
// 	$("#openFileModal").css('display','block');
// });
var m=angular.module('myApp',[]);
m.controller('test',['$scope','$filter',function($scope,$filter){
	$scope.openFileName=function(){
		$("#openFileModal").css('display','block');
		//获取文件列表
		var url = "http://" + window.location.hostname + ":1207" + "/cs/files";
		$.get(url,{ext:"UPG,XML", asJSON:false},function(result){
		//$.get(url,{ext:"PRG,UPG,LIB", asJSON:false},function(result){
			console.log(result);
			result = result.split(",");
			var list = [];
			for(var i=0;i<result.length;i++){
				var tmp = {"name":result[i]};
				list[i] = tmp;
			}

			//赋值 显示   //此处有问题 点击第一次没有 第二次才有
			$scope.allFile = list;	
			$scope.list = $scope.allFile;
		});
	}
	$scope.userFileName='';
	$scope.$watch('userFileName', function(newValue) {
        //当value改变时执行的代码
        $scope.list = $filter("filterName")($scope.allFile,"name",newValue);
    });
}]);
//自定义过滤器
m.filter("filterName",function(){
	return function(arr,key,value){
		if(value == ""){
			return arr;
		};
		var list = [];
		for(var i in arr){
			if(arr[i][key].indexOf(value) != -1){
				list.push(arr[i]);
			};
		};
		return list;
	};
});
//关闭文件名选择框
$("#closeFileModal").on('click',function(){
	$("#openFileModal").css('display','none');
});
//选择文件名
var oUl=document.getElementById("fileUl");
oUl.onclick=function(ev){
	ev=ev||window.event;
	var aLi=ev.target||ev.srcElement;//兼容不同的浏览器的事件源
	if(aLi.nodeName.toLowerCase()=='li'){
		$(aLi).addClass('active_f').siblings().removeClass('active_f');
	}
}

//打开文件:确定文件名,输出选择的文件名
$("#sureFileModal").on('click',function(){
	console.log($(".active_f").html());

	if(data_runstate == "stop" && data_model == "A"){
		var filename = $(".active_f").html();
	    var list = filename.split(".");
	    if(list[1] == "XML"){
	    	var url="http://"+window.location.hostname + ":1207"+"/cs/file/"+filename;
		    console.log(url);
		    $.get(url,function(result){
		        var oxml = Blockly.Xml.textToDom(result);
				console.log(oxml);
				Blockly.Xml.domToWorkspace(oxml, workspace);

				data_file_name = list[0];
				log("open file ok : name:"+data_file_name);

				//需要继续加载 upg(即是打开?)
		    	//setCurrentFile(list[0]+".UPG",true);
		    });
	    }
	    else{
	    	log("open file name wrong:not xml");
	    }  
	}
	else{
		log("机器正在运行或不是自动模式,不可操作文件");
	}
     
});

// 新建文件
function doUpLoadFile(filename,content){
	var locrul = "http://" + window.location.hostname + ":1207"+"/cs/upload";
    var formData = new FormData();//表单方式

    formData.append('file', new File([new Blob([content])], filename));

    $.ajax({ 
        contentType: "multipart/form-data;",
        url: locrul,
        type: 'POST', 
        data: formData,
        cache: false,
        contentType: false,
        processData: false, 
        success: function(result) { 
            if (result.err) {
                // do something with the error
                log(filename + " create failed");
            }
            else{
            	log(filename + " create ok");

            	//setCurrentFile(filename,true);//设置该文件为 当前文件
            }
        }
     });
}


// 保存文件
function doUpLoadFile_overide(filename,content){
	var locrul = "http://" + window.location.hostname + ":1207"+"/cs/upload/overwrite";
    var formData = new FormData();

    formData.append('file', new File([new Blob([content])], filename));
    
    $.ajax({ 
        contentType: "multipart/form-data;",
        url: locrul,
        type: 'POST', 
        data: formData,
        cache: false,
        contentType: false,
        processData: false, 
        success: function(result) { 
            if (result.err) {
                log(filename + " save failed!");
            }
            else{
            	log(filename + " save ok");

            	//setCurrentFile(filename,false);//设置当前文件
            }
        }
     });
}

//设置当前文件名(同时set_file_name指令内部会自动添加到namespace list)
//filename xxx.UPG  xxx.PRG
// function setCurrentFile(filename,setNameSpaceFlag){
// 	var index = filename.indexOf(".");
// 	var name = filename.substr(0,index);//前缀
// 	var ext = filename.substr(index+1);//后缀

// 	if (ext == "UPG" ){//|| ext == "PRG") {
// 		conn.queryMC('?TP_SET_FILE_NAME("' + filename + '")',function(result){
// 			console.log('?TP_SET_FILE_NAME("' + filename + '"):'+result);

// 			conn.queryMC('?TP_GET_NAMESPACE_LIST', function(result){
// 				console.log("?TP_GET_NAMESPACE_LIST:"+result)

// 				if(setNameSpaceFlag){ //打开文件 新建文件的时候需要设定工作区 保存不需要
// 					conn.queryMC('?TP_SET_NAMESPACE("' + name + '")', function(result){//加载完成后 自动设置当前工作域
// 							console.log('?TP_SET_NAMESPACE("' + name + '"):'+result);
// 					});
// 				}// else type = save
            	
// 				// sendData('?TP_GET_LONGS("")', updateLongs);
// 				// sendData('?TP_GET_STRINGS("")', updateStrings);
// 				// sendData('?TP_GET_DOUBLES("")', updateDoubles);
// 				// updateNamespaces(result);
// 			});

// 			handleError(result);
// 		});
// 	}
// }
